import mongoose from 'mongoose'
import rp from 'request-promise'
import {
  house_data,
  add_house_id
} from '~/database/socketData.js'

// 创建房间,防止在内存的数据中
export const creat_house = async (ctx, next) => {
  const random_arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'k', 'q'];
  const len = Object.keys(house_data).length;
  const Letter = random_arr[(Math.random().toString())[2]]
  let house_id = Letter + len;
  // 用对象总长度和随机字母生成房间号
  if (!house_data[house_id]) {
    add_house_id(house_id)
  } else {
    creat_house(ctx, next)
    return;
  }
  ctx.body = {
    state: 401,
    data: house_id
  }
  next()
}
// 查找房间,并判断房间房间状态
export const search_join_house = async (ctx, next) => {
  const time = parseInt(new Date().getTime() / 1000);
  const { openid} = ctx.query
  // 转成小写
  let  house_id = ctx.query.house_id.toLowerCase()
  if (!house_data[house_id]) {
    ctx.body = {
      state: 404,
      msg: '未找到房间',
      data: {}
    }
  } else if (house_data[house_id].members[openid]) {
    // 如果新加入成员原本就在房中，直接将房间状态返回，由前台跳转
    ctx.body = {
      state: 402,
      data: house_data[house_id]
    }
  } else if (house_data[house_id].status !== 0) {
    ctx.body = {
      state: 405,
      msg: '游戏已经开始不能中途加入',
      data: {}
    }
  } else {
    ctx.body = {
      state: 401,
      data: house_data[house_id]
    }
  }
  next()
}
// 返回微信密钥
export const get_appid_secret = async (ctx, next) => {
  const { appid } = ctx.query
  if (appid === 'wx54510ab8ae4abd58') {
    ctx.body = {
      state: 401,
      data: {
        secret: 'c876e971f1a11e4c5a056892dcba36b1',
        appid: 'wx54510ab8ae4abd58',
      }
    }
  } else {
    ctx.body = {
      state: 404,
      data: {
        secret: '',
        appid: 'wx54510ab8ae4abd58',
      }
    }
  }
  next()
}
// 请求微信openid
export const get_openid = async (ctx, next) => {
  const { js_code } = ctx.query
  if (!js_code) {
    ctx.body = {
      state: 404,
      data: '参数不齐'
    }
    next()
    return
  }
  const appid = 'wx54510ab8ae4abd58'
  const secret = 'c876e971f1a11e4c5a056892dcba36b1'
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`
  console.log('url:', url)
  const body = await rp(url)
  console.log('body:', body)
  ctx.body = {
    state: 401,
    data: body
  }
  next()
}
// 刚进入房间时获取房间信息，以及更新在线信息
export const get_house_info = async (ctx, next) => {
  const time = parseInt(new Date().getTime() / 1000);
  const {openid } = ctx.query
  // 转成小写
  let  house_id = ctx.query.house_id.toLowerCase()
  const creatHouse = mongoose.model('creatHouse')
  let ret = await creatHouse.findOne({ house_id: house_id }).exec();
  if (!ret) {
    ctx.body = {
      state: 404,
      data: {}
    }
    next()
    return
  }
  ret.members.forEach((item, index) => {
    if (item.openid === openid) {
      ret.members[index].updatedAt = time;
    }
    // 清除大于10秒还未在线发送信息的成员
    if (time - item.updatedAt >= 10) {
      ret.members.splice(index, 1)
    }

  })
  await ret.save()
  ret = await creatHouse.findOne({ house_id: house_id }).exec();
  ctx.body = {
    state: 401,
    data: ret
  }
  next()
}


export const random_str = () => {
  return new Promise(async (resolve, reject) => {
    const creatHouse = mongoose.model('creatHouse')
    const random_arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'k', 'q'];
    const Letter = random_arr[(Math.random().toString())[2]]
    let room_num = Letter + (Math.random().toString()).substring(2, 7)
    const test_ret = await creatHouse.findOne({ house_id: room_num }).exec();
    if (test_ret) {
      // 有重复的房号，重写
      random_str()
      return;
    }
    resolve(room_num)
  })
}

